﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SmartSpace.Core;
using SmartSapce.ServiceLocation;

namespace SmartSpace.WebApp._console.core
{
    public partial class org_add : System.Web.UI.Page
    {
        private Guid _selectedOrgId;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(Request.QueryString["id"]))
            {
                _selectedOrgId = new Guid(Request.QueryString["id"]);
            }

            if (!IsPostBack)
            {
                ICoreService service = ServiceLocator.Get<ICoreService>();
                Org parentOrg = service.GetOrg(_selectedOrgId);
                if (parentOrg != null)
                {
                    _ctlEditParent.Text = parentOrg.Caption;
                    _ctlLinkBack.NavigateUrl = string.Format("./org-list.aspx?id={0}", _selectedOrgId);
                }
                else
                {
                    _ctlEditParent.Text = "无";
                    _ctlLinkBack.NavigateUrl = "./org-list.aspx";
                }
            }
        }

        protected void _ctlBtnSave_Click(object sender, EventArgs e)
        {
            Org org = new Org();
            org.Id = Guid.NewGuid();
            org.Caption = _ctlEditCaption.Text;
            org.Code = _ctlEditCode.Text;
            org.Type = 1;

            ICoreService service = ServiceLocator.Get<ICoreService>();

            Org parentOrg = service.GetOrg(_selectedOrgId);
            if (parentOrg != null)
            {
                org.ParentId = parentOrg.Id;
            }

            service.SaveOrg(org);
            Response.Redirect(_ctlLinkBack.NavigateUrl);
        }

        protected void _ctlReset_Click(object sender, EventArgs e)
        {
            Response.Redirect("./org-add.aspx");
        }

        protected void _ctlBtnSaveAndContinue_Click(object sender, EventArgs e)
        {
            Org org = new Org();
            org.Id = Guid.NewGuid();
            org.Caption = _ctlEditCaption.Text;
            org.Code = _ctlEditCode.Text;
            org.Type = 1;

            ICoreService service = ServiceLocator.Get<ICoreService>();

            Org parentOrg = service.GetOrg(_selectedOrgId);
            if (parentOrg != null)
            {
                org.ParentId = parentOrg.Id;
            }

            service.SaveOrg(org);
            Response.Redirect(Request.Url.OriginalString);
        }
    }
}